/*****************************************************************************************
   
   Copyright (c) Microsoft Corporation. All rights reserved.

   Use of this code sample is subject to the terms of the Microsoft
   Permissive License, a copy of which should always be distributed with
   this file.  You can also access a copy of this license agreement at:
   http://www.microsoft.com/resources/sharedsource/licensingbasics/permissivelicense.mspx

 ****************************************************************************************/

using System;

namespace GrooveCommands
{
	class GrooveFormsTest : CommandUtils.GrooveUtilBase
	{
		private string m_SpaceURI;
		private string m_FormsToolURI;
		private string m_WhereClause;

		private bool m_Views;
		private bool m_Forms;
        private bool m_Fields;
        private bool m_UnusedFields;
		private bool m_CountOnly;
        private bool m_Sort;
		
		[STAThread]
		static void Main(string[] i_Arguments)
		{
			CommandUtils.UtilAppMain.RunApplication(new GrooveFormsTest(i_Arguments));
		}
	
		public GrooveFormsTest(string[] i_Arguments)
			: base (i_Arguments)
		{
			base.UsageMessage = "GrooveFormsTest [PARAMS...]";
			base.HelpMessage = 
				"GrooveFormsTest\r\n\t" + 
				"Displays summary information about Forms data in specified Groove workspace(s)\r\n" +
				"Parameters:\r\n\t" +
				"/Space=              The Web Services URI for the Groove workspace\r\n\t" +
				"[/FormsTool=         The Web Services URI for a specific Groove forms tool]\r\n\t" +
				"[/Views              Display details of each view]\r\n\t" +
				"[/Forms              Display details of each form]\r\n\t" +
                "[/Fields             Display details of all fields in the tool]\r\n\t" +
                "[/UnusedFields       Display details of all fields in the tool which don't appear on a form or view]\r\n\t" +
				"[/CountOnly          Display record counts only, not other information]\r\n\t" +
                "[/Sort               Sort field lists alphabetically]\r\n\t" +
				"[/Account=           The Web Services URI for the Groove account]\r\n\t" +
				"[/Identity=          The Web Services URI for the Groove identity]\r\n\t" +
				"[/WhereClause=       Query parameters (see Groove doc for syntax)]\r\n\t" +
				"[/RequestKey=        Token used to communicate Groove host]\r\n\t" +
				"[/Host=              The remote Groove host name to issue commands to]\r\n\t" +
				"[/Port=              The remote Groove host port to issue commands to]\r\n\t" +
				"[/Timeout=           Timeout (in ms) for Web Services method execution]\r\n\t" +
				"[/X=                 Configuration file to use for parameter input]\r\n\t" +
				"\r\n";
		}

		public override CheckResult CheckParameters()
		{
			CommandUtils.UtilBase.CheckResult CheckResult = base.CheckParameters();
			if (CheckResult != CommandUtils.UtilBase.CheckResult.Succeeded )
				return CheckResult;
		
			m_SpaceURI = base.GetParameterValue("Space");
            m_FormsToolURI = base.GetParameterValue("FormsTool");

            if (System.String.IsNullOrEmpty(m_SpaceURI) && System.String.IsNullOrEmpty(m_FormsToolURI))
			{
				base.DisplayUsage("You must specify a Space or a FormsToolURI.");
				return CommandUtils.UtilBase.CheckResult.Failed;
			}

            if (m_SpaceURI == null)
                m_SpaceURI = SpaceURIFromToolURI(m_FormsToolURI);

			m_WhereClause = base.GetParameterValue("WhereClause");
			if (System.String.IsNullOrEmpty(m_WhereClause))
				m_WhereClause = "";

			m_Views = base.GetParameterValueFlag("Views");
			m_Forms = base.GetParameterValueFlag("Forms");
            m_Fields = base.GetParameterValueFlag("Fields");
            m_UnusedFields = base.GetParameterValueFlag("UnusedFields");
            m_Sort = base.GetParameterValueFlag("Sort");
			m_CountOnly = base.GetParameterValueFlag("CountOnly");
			
			return base.CheckUnusedParameters();
		}

        private string SpaceURIFromToolURI(string i_FormsToolURI)
        {
            string[] URIParts = i_FormsToolURI.Split(new char[] { '/' });
            return "/GWS/Groove/2.0/Spaces/grooveTelespace/" + URIParts[6];
        }

		public override CommandUtils.UtilBase.CheckResult Run()
		{
			GrooveWebServicesV12Helpers.Space Space = null;

			try
			{
				Space = base.Identity.OpenSpace(m_SpaceURI);
			}
			catch (System.Exception Exception)
			{
				base.StandardError.WriteLine("Unable to open space: " + Exception.Message);
				throw Exception;
			}

			if (System.String.IsNullOrEmpty(m_FormsToolURI))
			{
                string[] SupportedTypes = new string[] { GrooveWebServicesV12Helpers.Shared.GROOVE_FORMS_TOOL_SUPPORTED_TYPE, GrooveWebServicesV12Helpers.Shared.GROOVE_FORMS2_TOOL_SUPPORTED_TYPE };
				GrooveWebServicesV12Helpers.Tool[] Tools = Space.GetToolsBySupportedTypes(SupportedTypes);
                foreach (GrooveWebServicesV12Helpers.Tool Tool in Tools)
				{
                    base.StandardError.WriteLine("Processing " + Tool.Name);
                    try
                    {
                        TestTool(Tool);
                    }
                    catch (Exception e)
                    {
                        base.StandardError.WriteLine(e.Message);
                        base.StandardError.WriteLine(e.StackTrace);
                    }
				}
			}
			else
			{
				GrooveWebServicesV12Helpers.Tool Tool;
				try
				{
					Tool = (GrooveWebServicesV12Helpers.Tool)Space.OpenTool(m_FormsToolURI);
				}
				catch (System.Exception Exception)
				{
					base.StandardError.WriteLine("Unable to open forms tool: " + Exception.Message);
					throw Exception;
				}
				TestTool(Tool);
			}

			return CommandUtils.UtilBase.CheckResult.Succeeded;
		}

        private void TestTool(GrooveWebServicesV12Helpers.Tool Tool)
        {
            base.StandardOutput.WriteLine("{0}", Tool.Name);
            base.StandardOutput.WriteLine("  {0}", Tool.URI);

            if (Tool is GrooveWebServicesV12Helpers.Forms.FormsTool)
            {
                GrooveWebServicesV12Helpers.Forms.FormsTool FormsTool = (GrooveWebServicesV12Helpers.Forms.FormsTool)Tool;

                if (!m_CountOnly)
                {
                    GrooveWebServicesV12Helpers.Forms.ToolProperties ToolProperties = FormsTool.ToolProperties;
                    base.StandardOutput.WriteLine("  Design name '{0}' version '{1}'", ToolProperties.DesignTemplateName, ToolProperties.DesignTemplateVersion);

                    base.StandardOutput.WriteLine("  Default form: '{0}'", ToolProperties.DefaultFormName);
                    base.StandardOutput.WriteLine("  Default view: '{0}'", ToolProperties.DefaultViewName);
                }

                GrooveWebServicesV12Helpers.Forms.RecordDataSet RecordDataSet = FormsTool.Records;
                base.StandardOutput.WriteLine("  Records: {0}", RecordDataSet.Data.Length);

                System.Collections.Hashtable fields = new System.Collections.Hashtable();
                System.Collections.Hashtable fieldsUsed = new System.Collections.Hashtable();

                if (m_Views || m_UnusedFields)
                {
                    foreach (GrooveWebServicesV12Helpers.Forms.View View in FormsTool.Views)
                    {
                        if (m_Views)
                        {
                            base.StandardOutput.WriteLine("  View '{0}'", View.Name);
                            RecordDataSet = FormsTool.QueryViewRecords(View.URI, m_WhereClause, false, false);
                            base.StandardOutput.WriteLine("    Records: {0}", RecordDataSet.Data.Length);
                        }
                        if (!m_CountOnly || m_UnusedFields)
                        {
                            GrooveWebServicesV12Helpers.Forms.Column[] Cols = View.Columns;
                            if (m_Views)
                            {
                                //						base.StandardOutput.WriteLine( "    Last modified record: {0}", View.LastModifiedRecordDateTime );
                                base.StandardOutput.WriteLine("    Default sort: {0}", View.DefaultSortPrimaryKeyName);
                                base.StandardOutput.WriteLine("    Columns: {0}", Cols.Length);
                            }
                            foreach (GrooveWebServicesV12Helpers.Forms.Column Col in Cols)
                            {
                                if (m_Views)
                                {
                                    base.StandardOutput.WriteLine("      '{0}' ('{1}')", Col.HeaderText, Col.Name);
                                }
                                if (!fields.ContainsKey(Col.Name))
                                {
                                    fields.Add(Col.Name, true);
                                }
                            }
                        }
                    }
                }

                if (m_Forms || m_UnusedFields)
                {
                    foreach (GrooveWebServicesV12Helpers.Forms.Form Form in FormsTool.Forms)
                    {
                        if (m_Forms)
                        {
                            base.StandardOutput.WriteLine("  Form '{0}'", Form.Name);
                            RecordDataSet = FormsTool.QueryFormRecords(Form.URI, m_WhereClause, false, false);
                            base.StandardOutput.WriteLine("    Records: {0}", RecordDataSet.Data.Length);
                        }
                        if (!m_CountOnly || m_UnusedFields)
                        {
                            GrooveWebServicesV12Helpers.Forms.Field[] Flds = Form.Fields;
                            if (m_Forms)
                            {
                                base.StandardOutput.WriteLine("    Fields: {0}", Flds.Length);
                            }
                            foreach (GrooveWebServicesV12Helpers.Forms.Field Fld in Flds)
                            {
                                if (m_Forms)
                                {
                                    base.StandardOutput.WriteLine("      '{0}' ('{1}'): {2}", Fld.Name, Fld.Label, Fld.DataType);
                                }
                                if (!fields.ContainsKey(Fld.Name))
                                {
                                    fields.Add(Fld.Name, true);
                                }
                            }
                        }
                    }
                }

                if (m_Fields)
                {
                    GrooveWebServicesV12Helpers.Forms.RecordDataSet schema = FormsTool.Schema;
                    foreach (System.Data.DataTable DataTable in RecordDataSet.ToDataSet().Tables)
                    {
                        System.Data.DataColumnCollection Cols = DataTable.Columns;
                        base.StandardOutput.WriteLine("  {0} Fields: {1}", DataTable.TableName, Cols.Count);
                        foreach (System.Data.DataColumn col in Cols)
                        {
                            base.StandardOutput.WriteLine("      '{0}': {1}", col.ColumnName, col.DataType);
                        }
                    }
                }

                if (m_UnusedFields)
                {
                    GrooveWebServicesV12Helpers.Forms.RecordDataSet schema = FormsTool.Schema;
                    System.Data.DataColumnCollection Cols = RecordDataSet.ToDataSet().Tables[0].Columns;
                    base.StandardOutput.WriteLine("  Unused Fields:");
                    foreach (System.Data.DataColumn col in Cols)
                    {
                        if (!fields.ContainsKey(col.ColumnName))
                        {
                            base.StandardOutput.WriteLine("      '{0}': {1}", col.ColumnName, col.DataType);
                        }
                    }
                }
            }
            else
            {
                GrooveWebServicesV12Helpers.Forms2.FormsTool FormsTool = (GrooveWebServicesV12Helpers.Forms2.FormsTool)Tool;

                if (!m_CountOnly)
                {
                    GrooveWebServicesV12Helpers.Forms2.ToolProperties ToolProperties = FormsTool.ToolProperties;
                    base.StandardOutput.WriteLine("  Design name '{0}' version '{1}'", ToolProperties.DesignTemplateName, ToolProperties.DesignTemplateVersion);

                    base.StandardOutput.WriteLine("  Default form: '{0}'", ToolProperties.DefaultFormName);
                    base.StandardOutput.WriteLine("  Default view: '{0}'", ToolProperties.DefaultViewName);
                }

                GrooveWebServicesV12Helpers.Forms2.RecordDataSet RecordDataSet = FormsTool.Records;
                base.StandardOutput.WriteLine("  Records: {0}", RecordDataSet.Data.Length);

                System.Collections.Hashtable fields = new System.Collections.Hashtable();
                System.Collections.Hashtable fieldsUsed = new System.Collections.Hashtable();

                if (m_Views || m_UnusedFields)
                {
                    foreach (GrooveWebServicesV12Helpers.Forms2.View View in FormsTool.Views)
                    {
                        if (m_Views)
                        {
                            base.StandardOutput.WriteLine("  View '{0}'", View.Name);
                            RecordDataSet = FormsTool.QueryViewRecords(View.URI, m_WhereClause, false, false);
                            base.StandardOutput.WriteLine("    Records: {0}", RecordDataSet.Data.Length);
                        }
                        if (!m_CountOnly || m_UnusedFields)
                        {
                            GrooveWebServicesV12Helpers.Forms2.Column[] Cols = View.Columns;
                            if (m_Views)
                            {
                                //						base.StandardOutput.WriteLine( "    Last modified record: {0}", View.LastModifiedRecordDateTime );
                                base.StandardOutput.WriteLine("    Default sort: {0}", View.DefaultSortPrimaryKeyName);
                                base.StandardOutput.WriteLine("    Columns: {0}", Cols.Length);
                            }
                            foreach (GrooveWebServicesV12Helpers.Forms2.Column Col in Cols)
                            {
                                if (m_Views)
                                {
                                    base.StandardOutput.WriteLine("      '{0}' ('{1}')", Col.HeaderText, Col.Name);
                                }
                                if (!fields.ContainsKey(Col.Name))
                                {
                                    fields.Add(Col.Name, true);
                                }
                            }
                        }
                    }
                }

                if (m_Forms || m_UnusedFields)
                {
                    foreach (GrooveWebServicesV12Helpers.Forms2.Form Form in FormsTool.Forms)
                    {
                        if (m_Forms)
                        {
                            base.StandardOutput.WriteLine("  Form '{0}'", Form.Name);
                            RecordDataSet = FormsTool.QueryFormRecords(Form.URI, m_WhereClause, false, false);
                            base.StandardOutput.WriteLine("    Records: {0}", RecordDataSet.Data.Length);
                        }
                        if (!m_CountOnly || m_UnusedFields)
                        {
                            GrooveWebServicesV12Helpers.Forms2.Field[] Flds = Form.Fields;
                            if (m_Forms)
                            {
                                base.StandardOutput.WriteLine("    Fields: {0}", Flds.Length);
                            }
                            foreach (GrooveWebServicesV12Helpers.Forms2.Field Fld in Flds)
                            {
                                if (m_Forms)
                                {
                                    base.StandardOutput.WriteLine("      '{0}' ('{1}'): {2}", Fld.Name, Fld.Label, Fld.DataType);
                                }
                                if (!fields.ContainsKey(Fld.Name))
                                {
                                    fields.Add(Fld.Name, true);
                                }
                            }
                        }
                    }
                }

                if (m_Fields)
                {
                    GrooveWebServicesV12Helpers.Forms2.RecordDataSet schema = FormsTool.Schema;
                    foreach (System.Data.DataTable DataTable in RecordDataSet.ToDataSet().Tables)
                    {
                        System.Data.DataColumnCollection Cols = DataTable.Columns;
                        base.StandardOutput.WriteLine("  {0} Fields: {1}", DataTable.TableName, Cols.Count);
                        foreach (System.Data.DataColumn col in Cols)
                        {
                            base.StandardOutput.WriteLine("      '{0}': {1}", col.ColumnName, col.DataType);
                        }
                    }
                }

                if (m_UnusedFields)
                {
                    GrooveWebServicesV12Helpers.Forms2.RecordDataSet schema = FormsTool.Schema;
                    System.Data.DataColumnCollection Cols = RecordDataSet.ToDataSet().Tables[0].Columns;
                    base.StandardOutput.WriteLine("  Unused Fields:");
                    foreach (System.Data.DataColumn col in Cols)
                    {
                        if (!fields.ContainsKey(col.ColumnName))
                        {
                            base.StandardOutput.WriteLine("      '{0}': {1}", col.ColumnName, col.DataType);
                        }
                    }
                }
            }
        }
	}
}